package com.tencent.ncnnyolox.basemodule

import com.tencent.ncnnyolox.BuildConfig
import com.yd.basemodule.interceptor.CommParamInterceptor
import com.yd.basemodule.interceptor.LoggingInterceptor
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * <pre>
 *     author : yh
 *     e-mail : xxx@xx
 *     time   : 2023/12/22
 *     desc   : 网络请求类
 * </pre>
 */
class NetWorkManager {

    private val BASE_URL_UAT = "http://shouyu.cargohu.com:8888"
    val BASE_URL = "http://shouyu.cargohu.com:8888"

    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
        private lateinit var retrofit: Retrofit
    }

    private object SingletonHolder {
        val INSTANCE = NetWorkManager()
    }

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(
                if (BuildConfig.DEBUG) {
                    BASE_URL_UAT
                } else {
                    BASE_URL
                }
            )
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(10L, TimeUnit.SECONDS)
            .addNetworkInterceptor(CommParamInterceptor())

            .addNetworkInterceptor(LoggingInterceptor())
            .writeTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(10L, TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .build()
    }

    fun <T> create(service: Class<T>?): T =
        retrofit.create(service!!) ?: throw RuntimeException("Api service is null!")

}